package mysql

import (
	"database/sql"
	"errors"
	"go.uber.org/zap"
)

// AddLike 添加点赞记录
func AddLike(userID, postID int64) error {
	sqlStr := `
        INSERT INTO post_vote (user_id, post_id) 
        VALUES (?, ?)
        ON DUPLICATE KEY UPDATE created_at = CURRENT_TIMESTAMP
    `
	_, err := db.Exec(sqlStr, userID, postID)
	if err != nil {
		zap.L().Error("添加点赞记录失败",
			zap.Int64("userID", userID),
			zap.Int64("postID", postID),
			zap.Error(err))
		return err
	}
	return nil
}

// RemoveLike 移除点赞记录
func RemoveLike(userID, postID int64) error {
	sqlStr := `DELETE FROM post_vote WHERE user_id = ? AND post_id = ?`
	result, err := db.Exec(sqlStr, userID, postID)
	if err != nil {
		zap.L().Error("移除点赞记录失败",
			zap.Int64("userID", userID),
			zap.Int64("postID", postID),
			zap.Error(err))
		return err
	}

	// 检查是否成功删除了记录
	rowsAffected, err := result.RowsAffected()
	if err != nil {
		zap.L().Error("获取受影响行数失败",
			zap.Int64("userID", userID),
			zap.Int64("postID", postID),
			zap.Error(err))
		return err
	}

	if rowsAffected == 0 {
		return errors.New("无相关点赞记录")
	}

	return nil
}

// LikeExists 判断点赞记录是否存在
func LikeExists(userID, postID int64) (bool, error) {
	sqlStr := `SELECT COUNT(1) FROM post_vote WHERE user_id = ? AND post_id = ?`
	var count int
	err := db.Get(&count, sqlStr, userID, postID)

	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return false, nil
		}
		zap.L().Error("查询点赞存在性失败",
			zap.Int64("userID", userID),
			zap.Int64("postID", postID),
			zap.Error(err))
		return false, err
	}

	return count > 0, nil
}

// ToggleLike 切换点赞状态
func ToggleLike(userID, postID int64) (exists bool, err error) {
	exists, err = LikeExists(userID, postID)
	if err != nil {
		return false, err
	}

	if exists {
		err = RemoveLike(userID, postID)
		if err != nil {
			return false, err
		}
		return false, nil // 移除后不存在
	} else {
		err = AddLike(userID, postID)
		if err != nil {
			return false, err
		}
		return true, nil // 添加后存在
	}
}
